import {Component, OnDestroy, OnInit} from '@angular/core';
import {Farm} from '../../../entity/farm.model';
import {FarmService} from '../../../service/farm.service';
import {LimitedTurbineLoadData} from './limited-turbine-load-data';
import {DataSourceService} from '../../../service/data-source/data-source.service';
import {DatePipe} from '@angular/common';
import {ApplicationService} from '../../../service/application.service';

@Component({
  selector: 'app-turbine-load',
  templateUrl: './turbine-load.component.html',
  styleUrls: ['./turbine-load.component.css'],
  providers: [DataSourceService]
})
export class TurbineLoadComponent implements OnInit, OnDestroy {

  private echartsIntance: any;
  public farmLoads: LimitedTurbineLoadData[] = [];   //风场的数据
  private totalLoad: LimitedTurbineLoadData = {      //第一行计算总数数据
    farmName: '总计',
    stationLoad: {code: '', value: 0},
    turbineLoad: {code: '', value: 0},
  };
  public options: object;

  private farmsNamesX: string[] = [];    //X轴数据
  private tLoad = [];         //风机负荷
  private sLoad = [];         //变电站负荷

  private maxLoad: number;  //图标的纵坐标

  constructor(
    private farmService: FarmService,
    private application: ApplicationService,
    private dataSource: DataSourceService,
    private datePipe: DatePipe
  ) {

  }

  ngOnInit() {
    this.farmLoads.push(this.totalLoad);
    this.initData();
    this.initOptions();
  }

  ngOnDestroy(): void {
    this.dataSource.dispose();
  }

  private series: any = [
    {
      name: '升压站负荷（MW）',
      type: 'bar',
      data: this.sLoad,
      barWidth: '38%',
      barGap: '15%',
      itemStyle: {
        normal: {
          color: 'rgb(219,83,46)'
        }
      }
    },
    {
      name: '设备负荷（MW）',
      type: 'bar',
      data: this.tLoad,
      barWidth: '38%',
      itemStyle: {
        normal: {
          color: 'rgb(116,214,73)'
        }
      }
    }
  ]

  initOptions() {
    let pipe = this.datePipe;
    this.options = {
      tooltip: {
        trigger: 'axis',
        formatter: function (params, ticket, callback) {
          let result = params[0].name + '&nbsp;&nbsp' + pipe.transform(new Date(), 'HH:mm:ss') + '</br>';
          params.forEach((item) => {
            result += item.marker + item.seriesName + ':' + item.value + '</br>';
          });

          return result;
        }
      },
      legend: {
        data: [
          {
            name: '升压站负荷（MW）',
            textStyle: {color: 'rgb(219,83,46)'}
          },
          {
            name: '设备负荷（MW）',
            textStyle: {color: 'rgb(116,214,73)'}
          }
        ],
      },
      grid: {
        left: '3%',
        right: '2%',
        bottom: '3%',
        containLabel: true
      },
      xAxis: [
        {
          type: 'category',
          data: this.farmsNamesX,
          axisPointer: {
            type: 'shadow'
          },
          axisLabel: {
            show: true,
            textStyle: {
              color: '#43a0b3',
              fontSize: 12
            },
            margin: 10
          },
          axisLine: {
            lineStyle: {
              color: '#35789d',
              width: 2
            }
          },
          axisTick: {
            show: false
          },
          splitLine: {
            show: true,
            lineStyle: {
              color: '#1b4268'
            }
          }
        }
      ],
      yAxis: [
        {
          type: 'value',
          name: '单位：MW',
          min: 0,
          // interval: 50,
          axisLabel: {
            formatter: '{value}',
            show: true,
            textStyle: {
              color: '#43a0b3'
            },
            margin: 17
          },
          axisLine: {
            lineStyle: {
              color: '#35789d',
              width: 2
            }
          },
          axisTick: {
            show: false
          },
          splitLine: {
            show: true,
            lineStyle: {
              color: '#1b4268'
            }
          }
        }
      ],
      series: this.series
    };
  }

  /**
   *推送
   *
   * @memberof TurbineLoadComponent
   */
  initData() {
    let farm = this.application.currentUserFarms
    this.createLimitedTurbineLoadData(farm);
    this.dataSource
      .begin()
      .subscribe(
        next => {
          this.sLoad = [];
          this.tLoad = [];
          let sumStationLoad = 0;
          let sumTurbineLoad = 0;
          for (let index = 1; index < this.farmLoads.length; index++) {
            let farmLoad = this.farmLoads[index];
            this.sLoad.push(farmLoad.stationLoad.value.toFixed(2));
            this.tLoad.push(farmLoad.turbineLoad.value.toFixed(2));
            sumStationLoad += farmLoad.stationLoad.value;
            sumTurbineLoad += farmLoad.turbineLoad.value;
          }
          let maxPower = Math.max.apply(Math, this.tLoad);  //实时负荷的最大值；
          this.series[0].data = this.sLoad;
          this.series[1].data = this.tLoad;

          //总负荷计算；
          this.totalLoad.stationLoad.value = sumStationLoad;
          this.totalLoad.turbineLoad.value = sumTurbineLoad;
          this.updateEchart();
        },
        error => {
          console.log('app-turbine-load', error);
        });

  }

  /**
   * 创建风场负荷对象(绑定点)
   *
   * @param {Farm[]} farms
   * @memberof TurbineLoadComponent
   */
  createLimitedTurbineLoadData(farms: Farm[]) {
    if (!farms) {
      return false;
    }
    let StationLoad = this.application.tagDict['StationLoad'];        //升压站负荷；
    let TurbineLoad = this.application.tagDict['Power'];        //风机负荷；
    farms.forEach(farm => {
      let load = {
        farmName: farm.farmName,
        //绑定数据
        stationLoad: this.dataSource.binding([farm.farmCode], StationLoad),
        //绑定数据
        turbineLoad: this.dataSource.binding([farm.farmCode], TurbineLoad),
      }
      this.farmLoads.push(load);
      this.tLoad.push(load.turbineLoad);
      this.sLoad.push(load.stationLoad);
      this.farmsNamesX.push(load.farmName);
    });

    this.updateEchart();
  }

  //初始化图表数据
  onChartInit(ec: any) {
    this.echartsIntance = ec;
  }

  //更新图表数据
  updateEchart() {
    if (this.echartsIntance != null)
      this.echartsIntance.setOption(this.options);
  }
}
